package com.meatball.game.util
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.listener.RedisMessageListenerContainer
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.StringRedisSerializer

@Configuration
class RedisConfig {

    /**
     * Redis 乱码问题
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    fun initRedisTemplate(redisTemplate: RedisTemplate<Any, Any>): RedisTemplate<Any, Any> {
        redisTemplate.keySerializer = StringRedisSerializer()
        redisTemplate.valueSerializer = GenericJackson2JsonRedisSerializer()
        redisTemplate.hashKeySerializer = StringRedisSerializer()
        redisTemplate.hashValueSerializer = GenericJackson2JsonRedisSerializer()
        return redisTemplate
    }

    /**
     * Redis 消息订阅(监听)者容器
     * <p>
     * 过期监听 1. redis配置打开 notify-keyspace-events Ex 2. 监听的类继承KeyExpirationEventMessageListener
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    fun redisMessageListenerContainer(redisConnectionFactory: RedisConnectionFactory): RedisMessageListenerContainer {
        val messageListenerContainer = RedisMessageListenerContainer()
        messageListenerContainer.setConnectionFactory(redisConnectionFactory)
        return messageListenerContainer
    }
}